import axios from 'axios'
import qs from 'qs'
axios.defaults.timeout = 20000
import {Dialog} from 'vant'
import VueCookies from 'vue-cookies';
import router from '@/router.js';

// axios.defaults.headers.post['Content-Type'] = 'application/x-www=form-urlencoded'
// axios.interceptors.request.use(config => {
//   console.log("config",config)
//   //return config
// }, e => {
  
// })
export default {
  async fetchGet(url, params = {}) {
    return await new Promise((resolve, reject) => {
      // let token = VueCookies.get('token')
      // if (token) { 
      //     axios.defaults.headers.common["token"] = token
      // }
      axios.get(url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  async fetchPost4login(url, data = {}) {
    return await new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(data)).then(res => {
  		  console.log("res",res)
  		 if(res.data.ret!=200){
  			 Dialog({ title:'温馨提示', message: res.data.msg.split('：')[1]||res.data.msg });
  		 }
  		 if(res.data.ret==401){
  			 router.replace('/login');
  		 }
        resolve(res.data)
      }).catch(error => {
  		  Dialog({ title:'系统提示', message: error });
          reject(error)
      })
    })
  },
  async fetchPost(url, data = {}) {
    return await new Promise((resolve, reject) => {
      // let token = VueCookies.get('token')
      // if (token) { 
      //     axios.defaults.headers.common["token"] = token
      // }
	  const token = VueCookies.get('token')
	  console.log("token",token)
	  if(token==null||token=='undefined'||token=='' || token==null){
		  const href = window.location.href
		  console.log("href",href)
		  console.log("href.split('#')[1]",href.split('#')[1])
		  if(href.split('#')[1]!='/login'){
			  router.replace('/login');
		  }
	  }
	  data.token = token;
	  if(!data.campus){
      data.campus = JSON.parse(localStorage.getItem('userInfo')).campus_id
    }
	  // data.campus_id = JSON.parse(localStorage.getItem('userInfo')).campus_id
	  data.users_id = JSON.parse(localStorage.getItem('userInfo')).id
      axios.post(url, qs.stringify(data)).then(res => {
		  console.log("res",res)
		 if(res.data.ret!=200){
			 Dialog({ title:'温馨提示', message: res.data.msg.split('：')[1]||res.data.msg });
		 }
		 if(res.data.ret==401){
			 router.replace('/login');
		 }
        resolve(res.data)
      }).catch(error => {
		  // Dialog({ title:'系统提示', message: error });
          reject(error)
      })
    })
  },
  fetchPostForUpload(url, data = {}) {
    return new Promise((resolve, reject) => {
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      } // 添加请求头
      axios.post(url, data, config).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}